package com.lam.common.utils.file;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lam.common.constant.CommonConstant;
import com.lam.common.utils.StringUtils;

/**
 * 文件处理工具类
 *
 * @author lam
 */
public class FileUtil extends IOUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static final String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
    private static final String USER_HOME = "~";

    /**
     * Simple factory for {@link File} objects but with home resolving.
     */
    public static File file(String fileName) {
        fileName = StringUtils.replace(fileName, USER_HOME, System.getProperty("user.home"));
        return new File(fileName);
    }

    /**
     * @see #mkdir(File)
     */
    public static boolean mkdir(String dir) {
        return mkdir(file(dir));
    }

    /**
     * 创建目录
     *
     * @param path 入参
     * @return boolean
     */
    public static boolean mkDirs(String path) {
        return new File(getDirFromPath(path)).mkdirs();
    }

    /**
     * Creates single directory.
     *
     * @throws IOException if cannot create directory.
     */
    public static boolean mkdir(File dir) {
        if (dir.exists()) {
            return true;
        }
        return dir.mkdirs();
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        return deleteFile(new File(filePath));
    }

    public static boolean deleteFile(File file) {
        if (file == null) {
            return false;
        }
        if (!file.exists()) {
            return false;
        }
        if (!file.isFile()) {
            return false;
        }
        try {
            Files.delete(Paths.get(file.getPath()));
            return true;
        } catch (IOException e) {
            logger.error("删除文件失败", e);
            return false;
        }
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String fileNameURLEncode(HttpServletRequest request, String fileName) {

        try {
            String agent = request.getHeader("USER-AGENT");
            String filename = fileName;
            if (agent.contains("MSIE")) {
                // IE浏览器
                filename = URLEncoder.encode(filename, CommonConstant.UTF8);
                filename = filename.replace("+", " ");
            } else if (agent.contains("Firefox")) {
                // 火狐浏览器
                filename = new String(fileName.getBytes(), "ISO8859-1");
            } else if (agent.contains("Chrome")) {
                // google浏览器
                filename = URLEncoder.encode(filename, CommonConstant.UTF8);
            } else {
                // 其它浏览器
                filename = URLEncoder.encode(filename, CommonConstant.UTF8);
            }
            return filename;
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
            return fileName;
        }
    }

    /**
     * 从路径中获取文件所在目录
     *
     * @param path
     * @return
     */
    public static String getDirFromPath(String path) {

        if (StringUtils.isBlank(path)) {
            return path;
        }

        int end = path.lastIndexOf('\\');
        if (end < 0) {
            end = path.lastIndexOf('/');
        }
        if (end > 0) {
            return path.substring(0, end);
        }
        return "";
    }
    
    /**
     * 从路径中获取文件名
     *
     * @param path
     * @return
     */
    public static String getFileNameFromPath(String path) {

        if (StringUtils.isBlank(path)) {
            return path;
        }

        path = path.replace('\\', '/');
        int start = path.lastIndexOf('/');
        if (start > 0) {
            return path.substring(start + 1);
        }
        return path;
    }
    
    /**
     * 从路径中获取文件名
     *
     * @param path
     * @return
     */
    public static String getFileSuffix(String fileName) {

        if (StringUtils.isBlank(fileName)) {
            return fileName;
        }

        int start = fileName.lastIndexOf('.');
        if (start < 0 || start == fileName.length()-1) {
            return "";
        }
        return fileName.substring(start+1);
    }
    
}
